package com.bana.sys.service;

import com.bana.sys.dao.*;
import com.bana.sys.model.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleService {

    @Resource
    private RoleDAO roleDAO;
    @Resource
    private RoleFunctionDAO roleFuncDAO;
    @Resource
    private UserRoleDAO userRoleDAO;
    @Resource
    private FunctionDAO functionDAO;

    public List<Role> getRoles(RolePageParameter rolePageParameter)
    {
        rolePageParameter.setYhmc("");
        List<Role> roles = roleDAO.getRoles(rolePageParameter);
        for(Role role:roles)
        {
            FunctionPageParameter functionPageParameter=new FunctionPageParameter();
            functionPageParameter.setJsbm(role.getJsbm());
            role.setFunctions(functionDAO.getFunctions(functionPageParameter));
        }
        return roles;
    }

    /**
     * 添加角色
     * @param role 角色
     */
    @Transactional
    public void insertRole(Role role)
    {
        roleDAO.insertRole(role);
        for(Function function : role.getFunctions())
        {
            RoleFuncion roleFunc=new RoleFuncion();
            roleFunc.setGnbm(function.getGnbm());
            roleFunc.setJsbm(role.getJsbm());
            roleFuncDAO.insertRoleFunction(roleFunc);
        }
    }

    /**
     * 更新角色
     * @param role 角色
     */
    @Transactional
    public void updateRole(Role role)
    {
        roleFuncDAO.deleteRoleFunctions(role.getJsbm());
        roleDAO.updateRole(role);
        for(Function function : role.getFunctions())
        {
            RoleFuncion roleFunc=new RoleFuncion();
            roleFunc.setGnbm(function.getGnbm());
            roleFunc.setJsbm(role.getJsbm());
            roleFuncDAO.insertRoleFunction(roleFunc);
        }
    }

    /**
     * 删除角色
     * @param jsbm 角色编码
     */
    @Transactional
    public void deleteRole(int jsbm)
    {
        userRoleDAO.deleteUserRoles(jsbm,"");
        roleFuncDAO.deleteRoleFunctions(jsbm);
        roleDAO.deleteRole(jsbm);
    }
}
